<template>
  <div style="width:100vw;display:flex;justify-content: center;background:#F9F9F9">
    <div class="container" style="width: 75vw;padding: 20px;padding-top: 0px;">
      <ExamNavBar :examId="examId" :semesterId="semesterId" />
      
      <form @submit.prevent="saveSettings" class="content-section">
        
        <!-- 考试模式 -->
        <div class="settings-box">
          <p class="section-title">考试模式</p>
          <div class="radio-group" style="margin: 10px 20px 20px 30px;" >
            <label v-for="mode in examModes" :key="mode.value">
              <input 
                type="radio" 
                v-model="formData.exam_mode" 
                :value="mode.value"
              /> {{ mode.label }}
            </label>
          </div>
        </div>

        <!-- 时间设置 -->
        <div class="settings-box">
          <p class="section-title">时间设置</p>
          <div class="form-group checkbox-group">
             <input type="checkbox" v-model="formData.is_during" true-value="1" false-value="0"/>
              <label>限时考试</label>
              <template v-if="formData.is_during == 1">
                <input 
                  type="number" 
                  v-model="formData.during_time" 
                  placeholder="考试时长(分钟)"
                  min="1"
                />
                 </template>
          </div>
          <div class="form-group">
            <label style="margin-left: 25px;">开始时间</label>
            <input type="datetime-local" v-model="formData.start_time"/>
          </div>
          <div class="form-group">
            <label style="margin-left: 25px;">结束时间</label>
            <input type="datetime-local" v-model="formData.end_time"/>
          </div>
        </div>

        <!-- 考试限制 -->
        <div class="settings-box">
          <p class="section-title">考试限制</p>
          <div class="form-group checkbox-group">
            <input type="checkbox" v-model="formData.is_late_time" true-value="1" false-value="0"/>
            <label>迟到限制</label>
            <template v-if="formData.is_late_time == 1">
              <input 
                type="number" 
                v-model="formData.late_time" 
                placeholder="迟到限制(分钟)"
                min="1"
              />
            </template>
          </div>
          <div class="form-group checkbox-group">
            <input type="checkbox" v-model="formData.is_earlier_time" true-value="1" false-value="0"/>
            <label>提前交卷</label>
            <template v-if="formData.is_earlier_time == 1">
              <input 
                type="number" 
                v-model="formData.earlier_time" 
                placeholder="允许提前时间(分钟)"
                min="1"
              />
            </template>
          </div>
        </div>

        <!-- 随机设置 -->
        <div class="settings-box">
          <p class="section-title">随机设置</p>
          <div class="checkbox-group" style="padding: 0px 30px 20px;gap: 20px;">
            <label><input type="checkbox" v-model="formData.is_qs_random" true-value="1" false-value="0"/> 小题顺序随机</label>
            <label><input type="checkbox" v-model="formData.is_option_random" true-value="1" false-value="0"/> 选项顺序随机</label>
            <label><input type="checkbox" v-model="formData.is_cv" true-value="1" false-value="0"/> 禁止复制粘贴</label>
          </div>
        </div>

        <!-- 密码设置 -->
        <div class="settings-box">
          <p class="section-title">密码设置</p>
          <div class="form-group checkbox-group">
            <input type="checkbox" v-model="formData.is_pwd" true-value="1" false-value="0"/>
            <label>考试密码</label>
            <template v-if="formData.is_pwd == 1">
              <input 
                type="text" 
                v-model="formData.start_pwd" 
                placeholder="输入考试密码"
              />
            </template>
          </div>
        </div>

        <!-- 提醒设置 -->
        <div class="settings-box">
          <p class="section-title">提醒设置</p>
          <div v-for="remind in formData.remind_list" :key="remind.exam_remind_id" class="form-group">
            <input 
              type="text" 
              v-model="remind.remind_content" 
              placeholder="提醒内容"
            />
            <input 
              type="number" 
              v-model="remind.remind_time" 
              placeholder="提前时间(分钟)"
              min="1"
            />
            <button type="button" @click="removeRemind(remind.exam_remind_id)" class="delete-btn">
              <img src="@/assets/picture/delete.png" alt="删除" class="btn-icon">
            </button>
          </div>
          <button type="button" @click="addRemind" class="add-btn">
            <img src="@/assets/picture/add.png" alt="添加" class="btn-icon">
          </button>
        </div>

        <!-- 操作按钮 -->
        <div class="button-group">
          <button type="submit" class="submit-button">保存</button>
          <button type="button" class="back-button" @click="$router.go(-1)">取消</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import { getExamSettings, updateExamSettings } from '@/services/api';
import ExamNavBar from '@/components/ExamNavBar.vue';

export default {
  name: 'ExamSettings',
  components: { ExamNavBar },
  setup() {
    const route = useRoute();
    const examId = route.params.examId;
    const semesterId = route.params.semesterId;
    const originalRemindList = ref([]);


    const examModes = ref([
      { label: '正式考试', value: 1 },
      { label: '模拟考试', value: 2 }
    ]);

    const formData = ref({
      exam_mode: 1,
      start_time: '',
      end_time: '',
      during_time: null,
      is_during: 0,
      is_late_time: 0,
      late_time: null,
      is_earlier_time: 0,
      earlier_time: null,
      is_cv: 0,
      is_qs_random: 0,
      is_option_random: 0,
      is_pwd: 0,
      start_pwd: '',
      remind_list: []
    });

// 修改加载设置方法
const loadSettings = async () => {
  try {
    const res = await getExamSettings(Number(examId));
    if (res.data.status === 1) {
      originalRemindList.value = res.data.data.remind_list || [];
      formData.value = { 
        ...res.data.data,
        remind_list: originalRemindList.value.map(item => ({
          exam_remind_id: item.exam_remind_id, // 保持原始ID
          remind_content: item.remind_content,
          remind_time: item.remind_time
        }))
      };
    }
  } catch (error) {
    console.error('获取设置失败:', error);
  }
};

// 修改保存设置方法
const saveSettings = async () => {
  try {
    // 处理提醒列表
    const currentRemindList = formData.value.remind_list;
    
     // 新增列表（无exam_remind_id的项）
    const remind_list = currentRemindList
      .filter(item => !item.exam_remind_id)
      .map(item => ({
        exam_id: Number(examId),
        remind_content: item.remind_content,
        remind_time: Number(item.remind_time) || 0
      }));

    // 更新列表（有exam_remind_id的项）
    const remind_updatelist = currentRemindList
      .filter(item => item.exam_remind_id)
      .map(item => ({
        exam_remind_id: Number(item.exam_remind_id),
        remind_content: item.remind_content,
        remind_time: Number(item.remind_time) || 0
      }));

    // 删除列表（原始数据中存在但当前不存在的项）
    const remind_dellist = originalRemindList.value
      .filter(originalItem => !currentRemindList.some(item => 
        item.exam_remind_id === originalItem.exam_remind_id
      ))
      .map(item => ({ exam_remind_id: Number(item.exam_remind_id) }));

    const params = {
      exam_id: Number(examId),
      exam_mode: formData.value.exam_mode,
      start_time: formData.value.start_time,
      end_time: formData.value.end_time,
      during_time: formData.value.during_time,
      is_during: formData.value.is_during,
      is_late_time: formData.value.is_late_time,
      late_time: formData.value.late_time,
      is_earlier_time: formData.value.is_earlier_time,
      earlier_time: formData.value.earlier_time,
      is_cv: formData.value.is_cv,
      is_qs_random: formData.value.is_qs_random,
      is_option_random: formData.value.is_option_random,
      is_pwd: formData.value.is_pwd,
      start_pwd: formData.value.start_pwd,
      remind_list,
      remind_updatelist,
      remind_dellist
    };
     // 添加调试日志
    console.log('新增列表:', remind_list);
    console.log('更新列表:', remind_updatelist);
    console.log('删除列表:', remind_dellist);

    const res = await updateExamSettings(params);
    if (res.data.status === 1) {
      ElMessage.success('设置保存成功！');
      await loadSettings(); // 重新加载获取最新数据
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败，请检查数据格式');
  }
};

// 修改添加提醒方法
const addRemind = () => {
  formData.value.remind_list.push({
    exam_remind_id: null, // 新增项设为null
    remind_content: '',
    remind_time: null
  });
};

const removeRemind = (examRemindId) => {
  formData.value.remind_list = formData.value.remind_list.filter(
    item => item.exam_remind_id !== examRemindId
  );
};

    onMounted(loadSettings);

    return {
      examId,
      semesterId,
      examModes,
      formData,
      saveSettings,
      addRemind,
      removeRemind
    };
  }
};
</script>

<style scoped>
label{
  font-size: 14px;
}
/* 复用原有样式基础上补充 */
.settings-box {
  border-bottom: 1px solid #eee;
}

.section-title {
  font-weight: 600;
  margin-bottom: 1rem;
  color: #333;
}

.form-group {
  display: flex;
  flex-direction: row;
  align-items: baseline;
  justify-content: flex-start;
  margin: 10px 20px 20px 30px;
}


.radio-group label {
  margin-right: 2rem;
}

.button-group {
  margin-top: 2rem;
  display: flex;
  gap: 1rem;
}
/* 优化容器样式 */
.content-section {
  background-color: #ffffff;
  padding: 20px 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

/* 统一输入框样式 */
input[type="checkbox"]{
  margin-right:10px ;
}

input[type="text"],
input[type="number"],
input[type="datetime-local"] {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 240px;
  transition: border-color 0.3s;
  margin: 0px 20px;
}

input:disabled {
  background-color: #f5f7fa;
}

/* 优化复选框组布局 */
.checkbox-group {
  display: flex;
  align-items: center;
}

/* 操作按钮样式优化 */
.button-group {
  margin-top: 30px;
  display: flex;
  gap: 20px;
  padding-left: 30px;
}

.submit-button {
  background-color: #244382;
  color: white;
  padding: 10px 35px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
}

.submit-button:hover {
  background-color: #3E66B0;
}
/* 图片按钮样式 */
.delete-btn, .add-btn {
  background: none;
  border: none;
  padding: 0;
  margin-left: 10px;
}

.btn-icon {
  width: 20px;
  height: 20px;
  vertical-align: middle;
}

/* 调整添加按钮位置 */
.add-btn {
  margin-left: 30px;
  padding: 8px 15px;
}

.back-button {
    background-color: #f0f0f0;
    color: #333;
    padding: 10px 40px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}
.back-button:hover {
    background-color: #C9C8C8;
    }

</style>